package com.thunder.soft.ui.activity;

import android.widget.Toast;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.thunder.soft.R;
import com.thunder.soft.bean.MyCollectBean;
import com.thunder.soft.common.base.BaseActivity;
import com.thunder.soft.common.util.ViewModelProviderHelper;
import com.thunder.soft.databinding.ActivityMyCollectBinding;
import com.thunder.soft.ui.adapter.MyCollectAdapter;
import com.thunder.soft.vm.MyCollectViewModel;

public class MyCollectActivity extends BaseActivity<ActivityMyCollectBinding> {
    private MyCollectViewModel myCollectViewModel;
    private MyCollectAdapter myCollectAdapter;

    @Override
    protected void initData() {
        myCollectViewModel = ViewModelProviderHelper.buildViewModel(this, MyCollectViewModel.class);
        getLifecycle().addObserver(myCollectViewModel);
        binding.setMyCollectViewModel(myCollectViewModel);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        binding.myCollectRecycler.setLayoutManager(linearLayoutManager);
        myCollectAdapter = new MyCollectAdapter();
        binding.myCollectRecycler.setAdapter(myCollectAdapter);
        binding.refreshLayout.autoRefresh();

        myCollectViewModel.getErrorMsg().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Toast.makeText(MyCollectActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        });

        myCollectViewModel.getMyCollectLiveData().observe(this, new Observer<MyCollectBean>() {
            @Override
            public void onChanged(MyCollectBean myCollectBeans) {
                if (myCollectBeans.getDatas().size() < 20) {
                    binding.refreshLayout.finishLoadMoreWithNoMoreData();
                }
                if (myCollectBeans.getCurPage() == 1) {
                    binding.refreshLayout.finishRefresh();
                    myCollectAdapter.addListClear(myCollectBeans.getDatas());
                } else {
                    myCollectAdapter.addList(myCollectBeans.getDatas());
                    binding.refreshLayout.finishLoadMore();
                }
            }
        });

        // 关闭页面
        myCollectViewModel.getFinishActivity().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                finish();
            }
        });
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_my_collect;
    }
}